/*
编写 : Hexh
时间 : 2012-6-15 9:02:48
*/
using System;
using System.ComponentModel;
using System.Web.Mvc;
using FsCarInfo.Core.Entity;
using FsCarInfo.Facade;
using HMIS.FrameWork;
using HMIS.Infrastructure.Core.Authority;
using HMIS.Infrastructure.Facade.Authority;
using HMIS.MVC.CommonSupport;
using HMIS.MVC.ViewModel;
using Iesi.Collections.Generic;
using System.Web;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace HMIS.MVC.Controllers
{
	/// <summary>
	///	 the mvc class of FsCarInventory
	/// </summary>
	public class FsCarInventoryController : BaseController
	{

		private readonly IFsCarInventoryFacade FsCarInventoryFacade;
		private readonly IHospUserFacade HospUserFacade;
		
		public FsCarInventoryController(IFsCarInventoryFacade FsCarInventoryFacade, IHospUserFacade HospUserFacade)
		{
			this.FsCarInventoryFacade = FsCarInventoryFacade;
			this.HospUserFacade = HospUserFacade;
		}
		
		[Description("访问FsCarInventory管理页面")]
		[ViewPage]
		public ActionResult FsCarInventory()
		{
			return View();
		}
		
		[ExtResult]
		[Description("添加修改FsCarInventory信息")]
		public ActionResult SaveOrUpdate()
		{
			FsCarInventory entity;
			if (String.IsNullOrEmpty(Request["Id"]))
			{
				entity = new FsCarInventory
				{
					InveDate = Request["InveDate"]==null ? DateTime.MinValue : DateTime.Parse(Request["InveDate"]), 
					DeptId = Request["DeptId"], 
					ReviUserId = Request["ReviUserId"], 
					State = Request["State"]==null ? 0 : int.Parse(Request["State"]), 
				};
			}
			else
			{
				// get the entity.
				entity = FsCarInventoryFacade.Get(Request["Id"]);
				// set new value..
				entity.InveDate = Request["InveDate"]==null ? DateTime.MinValue : DateTime.Parse(Request["InveDate"]); 
				entity.DeptId = Request["DeptId"]; 
				entity.ReviUserId = Request["ReviUserId"]; 
				entity.State = Request["State"]==null ? 0 : int.Parse(Request["State"]); 
			}			
			// TODO ..设置外键相关信息..
			/*
			string[] authusers = Request["AuthorizeUsers"].Split(',');
			for (int i = 0; i < authusers.Length; i++)
			{
				entity.AuthorizeUsers.Add(HospUserFacade.Load(authusers[i]));
			}
			*/
			// 保存信息
			FsCarInventoryFacade.SaveOrUpdate(entity);

			return this.JsonFormat(new ExtResult { success = true, id = entity.Id });
		}

		[ExtResult]
		[Description("创建库存盘点记录")]
		public ActionResult CreateNewInventory()
		{
			// 保存信息
			CurrentUser cUser = new CurrentUser();
			string inventID = FsCarInventoryFacade.CreateNewInventory(
				Request["DeptId"],
				Request["Type"],
				cUser.UserInfo.Id
				);

			return this.JsonFormat(new ExtResult { success = true, id = inventID });
		}

		[ExtResult]
		[Description("删除FsCarInventory基本资料")]
		public ActionResult Delete()
		{
			FsCarInventoryFacade.Delete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}
		
		[ExtResult]
		[Description("物理删除FsCarInventory基本资料")]
		public ActionResult PhysicsDelete()
		{
			FsCarInventoryFacade.PhysicsDelete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[Description("商品车盘点-文件上传处理")]
		public void InventoryFileUpload()
		{
			int rowCount = 0;
			string filename = String.Empty;
			string savePath = Server.MapPath("~/Uploads/");
			//读取批次信息
			FsCarInventory CarInvent = FsCarInventoryFacade.Get(Request["Id"]);
			logger.Info("待盘点批次为: " + Request["Id"]);
			logger.Info("待盘点车辆数:" + CarInvent.InvenCars.Count);

			HttpFileCollectionBase files = Request.Files; //获取客户端表单中的所有上传文件
			for (int i = 0; i < files.Count; i++)
			{
				HttpPostedFileBase hpf = files[i];
				filename = Path.GetFileName(hpf.FileName);//获取文件名称
				filename = savePath + filename; //获取服务端保存路径名称
				hpf.SaveAs(filename); //保存文件

				//读取文件判断
				logger.Info("盘点文件保存到:" + filename);
				//读取文件信息。
				List<FsCarInventoryList> itemList = LoadListFromUpFile(filename);
				//盘点记录
				foreach (FsCarInventoryList it in itemList)
				{
					var query = from ivcar in CarInvent.InvenCars
								where ivcar.CarId == it.CarId
								select ivcar;
					FsCarInventoryList ivcarItem = query.FirstOrDefault();
					if (ivcarItem != null)
					{
						ivcarItem.OperDate = it.OperDate;
						ivcarItem.OperUserId = it.OperUserId;
						rowCount++;
					}
				}
			}
			FsCarInventoryFacade.SaveOrUpdate(CarInvent);

			Response.Write("{\"success\":\"true\",\"message\":\"共处理[" + rowCount + "]条记录.\"}");
		}

		/// <summary>
		/// 读取盘点文件 到List中
		/// </summary>
		/// <param name="file"></param>
		/// <returns></returns>
		private List<FsCarInventoryList> LoadListFromUpFile(string file)
		{
			List<FsCarInventoryList> itemList = new List<FsCarInventoryList>();
			CurrentUser cUser = new CurrentUser();
			StreamReader sr = new StreamReader(file);
			while (!sr.EndOfStream)
			{
				string str = sr.ReadLine();				
				//开始一段
				try
				{
					if (str.Substring(0, 5) == "\"[ID:")
					{
						FsCarInventoryList invenCarInfo = new FsCarInventoryList();
						invenCarInfo.CarId = str.Substring(5, 36);
						// 读取全部信息
						for (int i = 0; i < 14; i++)
							str = str + sr.ReadLine();
						// 按 "," 分割
						string[] info = Regex.Split(str.Trim('"'), "\",\"");
						// 判断信息是否手工修改了
						long tp = long.Parse(info[3]); //timestamp
						string dt1 = (new DateTime(1970, 1, 1, 8, 0, 0)).Add(new TimeSpan(tp * 10000)).ToString();
						string dt2 = info[4].Replace("上午", "").Replace("上午", "");
						if (info.Length != 5 || info[0] != info[1] || info[2] != "QR_CODE" || dt1 != dt2)
						{
							throw new ValidationException("数据校验错!");
						}
						//处理信息.
						invenCarInfo.OperDate = dt1;
						invenCarInfo.OperUserId = cUser.UserInfo.Id;
						itemList.Add(invenCarInfo);
					}
				}
				catch (Exception ee)
				{
					sr.Close();
					logger.Error("分析文件发生错误:" + str + ee);
					throw new ValidationException("盘点文件格式异常!");
				}
			}
			sr.Close();
			return itemList;
		}

		[Description("获取FsCarInventory清单")]
		public ActionResult GetPlist()
		{
			long total;
			CurrentUser cUser = new CurrentUser();
			var data = FsCarInventoryFacade.GetPlist(
				cUser.UserInfo.DepartmentId,
				Request["state"],
				Request["type"],
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			//TODO : 修改关联查询返回的类型
			return this.JsonFormat(
				new ExtGirdData<FsCarInventory> { total = total, data = data },
				new string[] { "Department", "ReviUser" });
		}
		
		[Description("获取FsCarInventory信息")]
		public ActionResult GetById()
		{
			var entity = FsCarInventoryFacade.Get(Request["Id"]);
			return this.JsonFormat(
			   new ExtFormLoadData<FsCarInventory> { data = new FsCarInventory[] { entity } }, new string[] { "AuthorizeUsers" }
			   );
		}

		[ExtResult]
		[Description("判断FsCarInventory字段是否唯一")]
		public ActionResult IsFieldExist()
		{
			var result = FsCarInventoryFacade.IsFieldExist(Request["FieldName"], Request[Request["FieldName"]], Request["Id"]);
			return this.JsonFormat(new ExtResult { success = !result, msg = "已存在相同的项!" });
		}
	}
}
